<template>
	<view class="add-address">
		<div class="uForm">
			<u-form :border-bottom="false" :model="form" ref="uForm" :error-type="['toast']" :rule="rules">
				<u-form-item class="border" label="收货人" label-width="130" prop="name">
					<u-input v-model="form.name" clearable placeholder="请输入收货人姓名" />
				</u-form-item>
				<u-form-item label="手机号码" label-width="130" prop="mobile">
					<u-input v-model="form.mobile" type="number" maxlength="11" placeholder="请输入收货人手机号码" />
				</u-form-item>
				<u-form-item label="所在区域" label-width="130" prop="___path">
					<div @click="showPicker">
						{{ form.___path || '请选择所在地区' }}
					</div>
				</u-form-item>
				<u-form-item class="detailAddress" label="详细地址" label-width="130" prop="detail">
					<u-input type="textarea" v-model="form.detail" maxlength="100" height="150" placeholder="街道楼牌号等" />
				</u-form-item>
				<u-checkbox-group shape="circle" size="30">
					<u-checkbox :active-color="lightColor" v-model="form.isDefault">设为默认地址</u-checkbox>
				</u-checkbox-group>

				<div class="saveBtn" @click="save">保存</div>
			</u-form>

			<u-picker mode="multiSelector" v-model="show" :range="multiSelector" range-key="regionName"
				@columnchange="pickerChange" :default-selector='defaultSelect' @confirm="handlePickClick"></u-picker>

		</div>
	</view>
</template>
<script>
	import {
		addAddress,
		editAddress,
		getAddressDetail,
		getProvinces
	} from "@/api/address.js";
import storage from "../../../utils/storage";
	export default {

		methods: {
			// 保存当前 地址
			save() {
				
				if(!storage.getUserInfo().id){
					uni.navigateTo({
						url: '/pages/passport/login'
					})
				}
				this.$refs.uForm.validate((valid) => {
					if (valid) {
						let pages = getCurrentPages(); //获取页面栈
						let beforePage = pages[pages.length - 2]; //上个页面
						// 如果没有id则为新增地址
						if (!this.form.id) {

							const {
								arr,
								mobile,
								isDefault,
								name,
								detail
							} = this.form;
							addAddress({
								city: arr[1],
								detailAddress: detail,
								mobile,
								name,
								province: arr[0],
								region: arr[2],
								userId: storage.getUserInfo().id
							}).then((res) => {
								if (res.code == '000000') {
									uni.navigateBack();
								}
							});
						} else {

							const {
								arr,
								mobile,
								isDefault,
								name,
								detail,
								id
							} = this.form;
							editAddress({
								city: arr[1],
								detailAddress: detail,
								mobile,
								name,
								province: arr[0],
								region: arr[2],
								addressId: id
							}).then((res) => {
								if (res.code == '000000') {
									uni.navigateBack();
								}
							});
						}
					}
				});
			},

			pickerChange(val) {
				if (val.column == 0) {
					this.multiSelector[1] = [];
					this.multiSelector[2] = [];
					this.getpickerParentValue(1, val.index)
				}
				if (val.column == 1) {
					this.multiSelector[2] = [];
					this.getpickerParentValue(2, val.index)
				}
			},

			handlePickClick(val) {
				this.defaultSelect = val
				let arr = []
				val.forEach((item, index) => {
					arr.push(this.multiSelector[index][item].regionName)
				})

				let str = arr.join(',')
				this.$set(this.form, '___path', str)
				this.$set(this.form, 'arr', arr)

			},

			// 三级地址联动回调
			getpickerParentValue(type, index) {
				// 将需要绑定的地址设置为空，并赋值


				if (type == 0) {
					getProvinces({
						regionId: 0,
						regionLevel: 1
					}).then(res => {
						this.multiSelector[0] = res.data;
						this.getpickerParentValue(1, 0)
					})
				} else if (type == 1) {
					getProvinces({
						regionId: this.multiSelector[0][index].regionId,
						regionLevel: 2
					}).then(res => {
						this.$set(this.multiSelector, 1, res.data);
						this.getpickerParentValue(2, 0)
					})
				} else if (type == 2) {
					getProvinces({
						regionId: this.multiSelector[1][index].regionId,
						regionLevel: 3
					}).then(res => {
						this.$set(this.multiSelector, 2, res.data)
					})
				}


			},

			// 显示三级地址联动
			showPicker() {
				// this.$refs.cityPicker.show();
				this.show = true
			},
		},
		mounted() {},
		data() {
			return {
				defaultSelect: [0, 0, 0],
				lightColor: this.$lightColor, //高亮颜色
				mapFlag: false, // 地图选择开
				routerVal: "",
				form: {
					detail: "", //地址详情
					name: "", //收货人姓名
					mobile: "", //手机号码
					___path: "", //所在区域
					isDefault: false, //是否默认地址
					arr: []
				},
				multiSelector: [],
				show: false,
				// 表单提交校验规则
				rules: {
					name: [{
						required: true,
						message: "收货人姓名不能为空",
						trigger: ["blur", "change"],
					}, ],
					mobile: [{
							required: true,
							message: "手机号码不能为空",
							trigger: ["blur", "change"],
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: "手机号码不正确",
							trigger: ["change", "blur"],
						},
					],
					___path: [{
						required: true,
						message: "请选择所在区域",
						trigger: ["change"],
					}, ],
					detail: [{
						required: true,
						message: "请填写详细地址",
						trigger: ["blur", "change"],
					}, ],
				},
				list: [{
					id: "",
					localName: "请选择",
					children: [],
				}, ],
			};
		},
		onLoad(option) {
			if(!JSON.stringify(option) == '{}'){
				this.routerVal = JSON.parse(decodeURIComponent(option.info));
			}
			
			// 如果当前是编辑地址,则需要查询出地址详情信息
			if (this.routerVal.id) {
				const params = this.routerVal;
				params.___path = params.province + ',' + params.city + ',' + params.region;
				params.arr = [params.province, params.city, params.region];
				params.detail = params.detailAddress;

				this.$set(this, "form", params);
			}

			this.getpickerParentValue(0);
		},
		// 初始化rules必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
	};
</script>
<style scoped lang="scss">
	.detailAddress {
		/deep/ .u-form-item--left {
			display: flex;
			align-items: flex-start;
		}
	}

	.saveBtn,
	.selectAddress {
		height: 70rpx;

		line-height: 70rpx;
		text-align: center;
		font-size: 30rpx;
		background: $aider-light-color;
		color: #fff;
		width: 70%;
		margin: 40rpx auto 0 auto;
		border-radius: 20rpx;
	}

	.selectAddress {
		margin-top: 40rpx;
		background: #fff;

		color: $aider-light-color;
		border: 2rpx solid $aider-light-color;
	}

	.uForm {
		width: 94%;
		overflow: hidden;
		left: 3%;
		position: relative;
		top: 2%;
		background: #fff;
		border-radius: 20rpx;
		padding: 0 0 40rpx 0;
	}

	.add-address {
		width: 100%;
		padding-top: 3%;

		/deep/ .u-form-item {
			background-color: #fff;
			padding: 24rpx 30rpx;
		}

		.u-btn {
			margin: 30rpx 30rpx 0 30rpx;
			background-color: $main-color;
		}

		/deep/.u-checkbox {
			margin: 30rpx 30rpx 0 30rpx;

			.u-label-class.u-checkbox__label {
				color: $font-color-light;
				font-size: $font-sm;
			}
		}
	}

	/deep/ .u-checkbox__label {
		font-size: 28rpx;
	}
</style>
